package com.leyou.auth.service;

import com.leyou.auth.config.JwtProperties;
import com.leyou.common.auth.domain.Payload;
import com.leyou.common.auth.domain.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.exception.domain.ExceptionEnum;
import com.leyou.common.exception.domain.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class AuthService {
    @Autowired
    private UserClient userClient;
    @Autowired
    private JwtProperties prop;
    @Autowired
    private StringRedisTemplate redisTemplate;
    //登录操作业务代码
    public void login(String username, String password, HttpServletResponse response) {
        //验证用户名和密码是否正确
        UserDTO userDTO = userClient.queryUser(username, password);
        //将UserDto转成UserInfo
        UserInfo userInfo = new UserInfo(userDTO.getId(), userDTO.getUsername(), "admin");
        //创建token，并直接写回到浏览器的cookie中
        createTokenToCookie(response, userInfo);
    }

    /**
     * 创建token的方法ctrl+alt+m，并直接写回到浏览器的cookie中
     * @param response
     * @param userInfo
     */
    private void createTokenToCookie(HttpServletResponse response, UserInfo userInfo) {
        //生成token
        String token = JwtUtils.generateTokenExpireInMinutes(userInfo, prop.getPrivateKey(), prop.getUser().getExpire());
        //将token写回浏览器的cookie中
        CookieUtils.newCookieBuilder()
                .response(response)
                .name(prop.getUser().getCookieName())
                .value(token)
                .httpOnly(true)
                .domain(prop.getUser().getCookieDomain())
                .build();
    }
    /**
     * 在页面上显示当前认证通过的用户名提供处理器
     */
    public UserInfo verifyUser(HttpServletRequest request, HttpServletResponse response) {
        //获取cookie中token
        String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());
        if (StringUtils.isBlank(token)){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }

        /**
         * 验证token是否合法
         *
         */
        Payload<UserInfo>payload=null;

        try {
            payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
        } catch (Exception e) {
          throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        //获取当前token的id
        String tokenId = payload.getId();
        //判断当前token是否在黑名单
        if (redisTemplate.hasKey(tokenId)){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }


        //得到载荷中的用户信息
        UserInfo userInfo = payload.getUserInfo();

        /**
         * 修改token的刷新点时间，
         */

        //得到token中的过期时间
        Date expiration = payload.getExpiration();
        //得到刷新点
        DateTime refreshTime = new DateTime(expiration).minusMillis(prop.getUser().getRefreshTime());
        //如果刷新时间在当前时间之前，就刷新token
        if (refreshTime.isBefore(System.currentTimeMillis()
        )){
            //重新生成token并写入到cookie中
            createTokenToCookie(response,userInfo);

        }
        return userInfo;


    }

    /**
     * 退出登录
     */

    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //获取token
        String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());
        if (StringUtils.isBlank(token)){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);

        }
        //验证token是否合法
        Payload<Object> payload=null;
        try {
            payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey());
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        //获取token的id
        String tokenId = payload.getId();
        //获取当前token的剩余过期时间,单位是毫秒
        long remainTime = payload.getExpiration().getTime() - System.currentTimeMillis();
        //将当前的token加入黑名单
        if(remainTime>1000) {
            redisTemplate.opsForValue().set(tokenId, "1", remainTime, TimeUnit.MILLISECONDS);
            //删除token
            CookieUtils.deleteCookie(prop.getUser().getCookieName(), prop.getUser().getCookieDomain(), response);

        }
    }
}
